using System;
using System.Collections.Generic;

namespace Wodewick
{
	public class Biggus
	{
		private List<Level> levels = new List<Level>
									{
										new Level
											{
												upper = new Map(1000, "M"),
												mid = new Map(500, "D"),
												lower = new Map(100, "C")
											},
										new Level
											{
												upper = new Map(100, "C"),
												mid = new Map(50, "L"),
												lower = new Map(10, "X")
											},
										new Level
											{
												upper = new Map(10, "X"),
												mid = new Map(5, "V"),
												lower = new Map(1, "I")
											}
									};


		public string Convert(int input)
		{
			var result = "";
			result = RenderExcess(input, levels[0].upper);
			foreach (var level in levels)
				result += level.ConvertLevel(input);
			return result;
		}

		private string RenderExcess(int input, Map upper)
		{
			var sig = input - (input%upper.Value);
			return new string(upper.Symbol[0], sig/upper.Value);
		}
	}

	public class Level
	{
		public Map upper { get; set; }
		public Map mid { get; set; }
		public Map lower { get; set; }

		public string ConvertLevel(int input)
		{
			var significant = GetSignificantInputValue(input);

			var result = "";

			if (significant == upper.Value - lower.Value)
				result += lower.Symbol + upper.Symbol;
			else if (significant > mid.Value)
				result += mid.Symbol + new string(lower.Symbol[0], (significant - mid.Value)/ lower.Value);
			else if (significant == mid.Value)
				result += mid.Symbol;
			else if (significant == mid.Value - lower.Value)
				result += lower.Symbol + mid.Symbol;
			else
				result += new string(lower.Symbol[0], (significant / lower.Value));

			return result;
		}

		public int GetSignificantInputValue(int input)
		{
			var result = input % upper.Value;
			result = result - result % lower.Value;
			return result;
		}
	}

	public class Map
	{
		public int Value { get; set; }
		public string Symbol { get; set; }

		public Map(int value, string symbol)
		{
			Value = value;
			Symbol = symbol;
		}
	}

}